import type { ColumnsSettingType, ColumnsTypeDrawerPropsType, TableColumnProps } from './typings'
import { defineComponent, ref, onMounted } from 'vue'
import {
  ElDialog,
  ElScrollbar,
  ElLink,
  ElRow,
  ElCol,
  ElCheckbox,
  ElSpace,
  ElButton
} from 'element-plus'
import { WarningFilled } from '@element-plus/icons-vue'
import Vuedraggable from 'vuedraggable'
import AliIcon from '../AliIocn'
// import { GUTTER } from '~/utils/const'
import styles from './index.module.scss'

const columnsSettingCol = {
  checkbox: 3,
  columnLabel: 17,
  sort: 4
}

export default defineComponent({
  name: 'ColumnsTypeDrawer',
  props: ['tableId', 'visible', 'columns', 'filterColumns', 'onClose'],
  emits: ['changeSettingColumns'],
  setup(props: ColumnsTypeDrawerPropsType, { emit }) {
    const customColumnRef = ref<(TableColumnProps<any> & { show: boolean })[]>()

    // 重置columns为原始状态
    const handleResetDefaultColumns = () => {
      customColumnRef.value = props.columns?.map((item) => ({ ...item, show: !item?.hidden }))
    }

    // 确认当前的columns配置并发送给父组建
    const handleChangeColumnsSettings = () => {
      emit(
        'changeSettingColumns',
        customColumnRef.value?.reduce(
          (columnsSetting: ColumnsSettingType, item, index) =>
            Object.assign(columnsSetting, { [item.prop]: { show: item.show, sort: index } }),
          {}
        )
      )
      props.onClose()
    }

    onMounted(() => {
      const localColumnsSetting: ColumnsSettingType =
        props.tableId && JSON.parse(localStorage.getItem(props.tableId) as string)

      if (localColumnsSetting) {
        customColumnRef.value = props.columns
          ?.map((item) => ({
            ...item,
            show: item.prop in localColumnsSetting ? localColumnsSetting[item.prop].show : false
          }))
          .sort(
            (prev, next) =>
              localColumnsSetting[prev.prop]?.sort - localColumnsSetting[next.prop]?.sort
          )
      } else {
        customColumnRef.value = props.columns?.map((item) => ({
          ...item,
          show: !item?.hidden
        }))
      }
    })

    return () => (
      <ElDialog
        customClass={styles['pro-saas-table-custom-column']}
        title="自定义表头"
        width="750px"
        closeOnClickModal={false} // 点遮罩层不关弹窗
        draggable // 可拖拽
        modelValue={props.visible}
        beforeClose={props.onClose}
        v-slots={{
          footer: () => (
            <ElRow justify="space-between">
              <ElCol span={3}>
                <ElButton size="default" type="primary" plain onClick={handleResetDefaultColumns}>
                  恢复默认
                </ElButton>
              </ElCol>
              <ElCol span={6}>
                <ElSpace>
                  <ElButton size="default" type="primary" plain onClick={props.onClose}>
                    取消
                  </ElButton>
                  <ElButton size="default" type="primary" onClick={handleChangeColumnsSettings}>
                    确定
                  </ElButton>
                </ElSpace>
              </ElCol>
            </ElRow>
          )
        }}
      >
        <ElLink
          type="info"
          underline={false}
          class={styles['columns-setting-info']}
          icon={WarningFilled}
        >
          灰色选中列表不支持隐藏和排序
        </ElLink>
        <ElScrollbar class={styles['columns-setting-scroll']} height={412}>
          <ElRow
            class={{
              [styles['columns-setting-title']]: true,
              [styles['columns-setting-item']]: true
            }}
          >
            <ElCol span={columnsSettingCol.checkbox}>显示</ElCol>
            <ElCol span={columnsSettingCol.columnLabel}>列名</ElCol>
            <ElCol span={columnsSettingCol.sort}>拖动调整顺序</ElCol>
          </ElRow>
          <Vuedraggable
            v-model={customColumnRef.value}
            itemKey="prop"
            tag="ul"
            class={styles['columns-setting-list']}
          >
            {{
              item: ({ element }: { element: TableColumnProps<any> & { show: boolean } }) => (
                <li>
                  <ElRow class={styles['columns-setting-item']}>
                    <ElCol span={columnsSettingCol.checkbox}>
                      <ElCheckbox v-model={element.show} disabled={element.disabled} />
                    </ElCol>
                    <ElCol span={columnsSettingCol.columnLabel}>{element.label}</ElCol>
                    <ElCol span={columnsSettingCol.sort}>
                      <ElLink
                        disabled={element.disabled}
                        type={element.disabled ? 'info' : 'primary'}
                        underline={false}
                      >
                        <AliIcon type="icon-tuodongtiaozhengshunxu" />
                      </ElLink>
                    </ElCol>
                  </ElRow>
                </li>
              )
            }}
          </Vuedraggable>
        </ElScrollbar>
      </ElDialog>
    )
  }
})
